package cn.legend.travel.admin.comment.filter;

import cn.legend.travel.admin.comment.dao.cache.IUserCacheRepository;
import cn.legend.travel.common.enumerator.ServiceCode;
import cn.legend.travel.common.pojo.authentication.CurrentPrincipal;
import cn.legend.travel.common.pojo.po.UserStatePO;
import cn.legend.travel.common.util.JwtUtils;
import cn.legend.travel.common.web.JsonResult;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthorizationFilter extends OncePerRequestFilter {
    @Value("${travel.jwt.secret-key}")
    private String secretKey;
    private final IUserCacheRepository repository;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        String jwt = request.getHeader("Authorization");
        if (!shouldFilter(request.getRequestURI(), jwt)) {
            filterChain.doFilter(request, response);
            return;
        }
        jwt = jwt.replace("Bearer", "").trim();
        try {
            CurrentPrincipal principal = getPrincipal(jwt, response);
            List<SimpleGrantedAuthority> authorities = getAuthorities(principal.getId(), response);
            if (authorities != null) {
                Authentication authenticationToken = new UsernamePasswordAuthenticationToken(principal, null, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                filterChain.doFilter(request, response);
            }
        } catch (Exception e) {
            log.trace(e.getMessage());
        }
    }

    private List<SimpleGrantedAuthority> getAuthorities(Long id, HttpServletResponse response) {
        UserStatePO userState = repository.getUserState(id);
        if (userState == null) {
            String message = "登录已过期.";
            handleResponse(ServiceCode.ERROR_UNAUTHORIZED, message, response);
            throw new RuntimeException();
        }
        if (userState.getState() == 0) {
            String message = "账号已被禁用.";
            handleResponse(ServiceCode.ERROR_UNAUTHORIZED_DISABLED, message, response);
            throw new RuntimeException();
        }
        repository.expire(id);
        return JSON.parseArray(userState.getAuthoritiesJsonString(), SimpleGrantedAuthority.class);
    }

    private CurrentPrincipal getPrincipal(String jwt, HttpServletResponse response) {
        Claims claims;
        try {
            claims = JwtUtils.parse(jwt, secretKey);
        } catch (MalformedJwtException e) {
            handleResponse(ServiceCode.ERR_JWT_MALFORMED, "非法访问!", response);
            throw new RuntimeException(e);
        } catch (SignatureException e) {
            handleResponse(ServiceCode.ERR_JWT_SIGNATURE, "非法访问!", response);
            throw new RuntimeException(e);
        } catch (Throwable e) {
            handleResponse(ServiceCode.ERROR_UNKNOWN, "服务器忙,请稍后再试!", response);
            throw new RuntimeException(e);
        }
        Long id = claims.get("id", Long.class);
        String username = claims.get("username", String.class);
        CurrentPrincipal principal = new CurrentPrincipal();
        principal.setId(id);
        principal.setUsername(username);
        return principal;
    }

    private boolean shouldFilter(String requestURI, String jwt) {
        if (requestURI.endsWith(".js") || requestURI.endsWith(".css")) {
            return false;
        }
        return StringUtils.hasText(jwt);
    }

    @SneakyThrows
    private void handleResponse(ServiceCode serviceCode, String message, HttpServletResponse response) {
        JsonResult fail = JsonResult.fail(serviceCode, message);
        String jsonString = JSON.toJSONString(fail);
        response.setContentType("application/json; charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.println(jsonString);
    }
}
